import React from 'react';
import {connect} from 'react-redux';
class ImReduxApp extends React.Component{
    constructor(props){
        super(props);
        this.nameRef=React.createRef();
        this.descRef=React.createRef();
    }

    delHobby(item){
        this.props.delHobby(item)
    }

    addHobby(){
        const item={
            name:this.nameRef.current.value,
            desc:this.descRef.current.value
        }
        this.props.addHobby(item);
        this.nameRef.current.value='';
        this.descRef.current.value='';
    }

    render(){
        console.log(this.props)
        const {name,age}=this.props;
        const{city,region}=this.props.address;
        return(
            <div>
               <h2>姓名：{name}</h2> 
               <h2>年龄：{age}</h2> 
               <h2>城市：{city}</h2> 
               <h2>区域：{region}</h2> 
               <ul>
                   {
                       this.props.hobbies.map((item,index)=>{
                           return <li key={item.get('name')}>
                               <span>{item.get('name')},</span>
                               <span>{item.get('desc')}</span>
                               <button style={{marginLeft:'20px'}} onClick={e=>this.delHobby(item)}>删除</button>
                           </li>
                       })
                   }
               </ul>
               <input ref={this.nameRef}/>
               <input ref={this.descRef}/>
               <button onClick={e=>this.addHobby()}>新增</button>
            </div>
        )
    }
}

function mapStateTOProps(state){
    return{
        name:state.get('name'),
        age:state.get('age'),
        address:state.get('address').toJS(),
        hobbies:state.get('hobbies')

    }
}

function mapDispatchToProps(dispatch){
    return{
        delHobby(item){
            dispatch({type:'DEL_HOBBY',item:item})
        },
        addHobby(item){
            dispatch({type:'ADD_HOBBY',item:item})
        }
    }
}

let NewImReduxApp=connect(mapStateTOProps,mapDispatchToProps)(ImReduxApp)

export default NewImReduxApp
